<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 게시판 글 관리 컨트롤러
 */
class Bbs extends CI_Controller {
	
	var $data = array();
	
	function __construct() {
		parent::__construct();
		
		$this->load->model('bbs/Bbs_model', 'model');
		$this->load->helper(array('pagenavi'));
	}
	
	// Default
	function index() {
		$this->bbs_list();
	}
	
	/**
	 * 게시물 리스트
	 */
	function bbs_list() {
		log_message('debug', "@@@@ Bbs::bbs_list()");
		
		$cate           = $this->input->get('cate', TRUE);
		$search_type    = $this->input->get('search_type', TRUE);
		$search_keyword = $this->input->get('search_keyword', TRUE);
		$page           = $this->input->get('page', TRUE);

		$cate           = empty($cate) ? '' : $cate;
		$search_type    = empty($search_type) ? '' : $search_type;
		$search_keyword = empty($search_keyword) ? '' : $search_keyword;
		$current_page   = empty($page) ? 1 : $page;

		$page_size  = LIST_PAGE_SIZE;	// 한 페이지에 보여줄 글 수
		$block_size = LIST_BLOCK_SIZE;	// 네비영역의 한 블록에 보여줄 페이지 수

		$total_cnt  = $this->model->get_bbs_total_count($cate, $search_type, $search_keyword);	// 총 글 수
		
		$this->data['list'] = $this->model->select_bbs_list($cate, $search_type, $search_keyword, $current_page, $page_size);
		
		$this->data['navi'] = page_navigation($current_page, $total_cnt, $page_size, $block_size);
		
		$this->data['cates'] = array(
			  'postscript'=>"운세후기"
			, 'free'=>"자유게시판"
			, 'event'=>"이벤트"
			, 'event_notice'=>"이벤트당첨자"
			, 'notice'=>"공지사항"
			, 'faq'=>"자주하는 질문"
			, 'qna'=>"1:1 문의"
			, 'imbc_notice'=>"공지사항(iMBC)"
			, 'imbc_faq'=>"자주하는 질문(iMBC)"
			, 'imbc_event'=>"이벤트(iMBC)"
			, 'imbc_event_notice'=>"이벤트당첨자(iMBC)"
		);
		
		$this->load->view('bbs/bbs_list_v.php', $this->data);
	}
	
	/**
	 * 상세 정보
	 */
	function detail() {
		log_message('debug', "@@@@ Bbs::detail()");
		
		$idx = $this->input->get('idx', TRUE);
		$this->data['content'] = $this->model->get_bbs_content($idx);
		$this->data['reply_list'] = $this->model->select_bbs_reply_list($idx);

		
		$this->load->view('bbs/detail_pop_v.php', $this->data);
	}
	
	/**
	 * 글쓰기 폼
	 */
	function write() {
		log_message('debug', "@@@@ Bbs::write()");
		
		$this->load->view('bbs/write_v', $this->data);
	}
	
	/**
	 * 글쓰기 완료
	 */
	function write_ok() {
		log_message('debug', "@@@@ Bbs::write_ok()");
		
		// 글 저장
		$bbs_content['category']   = $this->input->post('cate', TRUE);
		$bbs_content['user_id']    = $this->data['sess_userinfo']['user_id'];
		$bbs_content['nickname']   = $this->data['sess_userinfo']['nickname'];
		$bbs_content['subject']    = $this->input->post('subject', FALSE);
		$bbs_content['content']    = $this->input->post('content', FALSE);

		// 파일 저장 
		$result_upload = $this->_do_upload($bbs_content['category']);
		log_message('debug', "@@ result_upload=".print_r($result_upload, TRUE));
		

		$this->model->save_bbs($bbs_content, $result_upload);

		redirect("/bbs/");
	}

	/**
	 * 파일 업로드
	 */
	function _do_upload($cate) {
		log_message('debug', "@@@@ Bbs::_do_upload($cate)");

		if ($cate == 'imbc_notice' || $cate == 'imbc_faq' || $cate == 'imbc_event' || $cate == 'imbc_event_notice') {
			$upload_dir = FILE_UPLOAD_DIR_IMBC;
			$upload_url = FILE_UPLOAD_URL_IMBC;
		} else {
			$upload_dir = FILE_UPLOAD_DIR_UNSIN;
			$upload_url = FILE_UPLOAD_URL_UNSIN;
		}
		$target_dir = $upload_dir.$cate."/".date('Ym',time());
		$target_url = $upload_url.$cate."/".date('Ym',time());

		log_message('debug','@@ target_dir='.$target_dir);
		
		if(!is_dir($target_dir)){
		   mkdir($target_dir, DIR_WRITE_MODE);
		}
		
		$config['upload_path']   = $target_dir;
		$config['allowed_types'] = 'gif|jpg';
		$config['max_filename']  = '255';
		// $config['max_size']      = '1024';
		// $config['max_width']     = '1920';
		// $config['max_height']    = '1080';
		$config['encrypt_name']  = TRUE;
		$config['remove_spaces'] = TRUE;
		
		$this->load->library('upload', $config);
		
		if ( ! $this->upload->do_upload()) {
			$result = $this->upload->display_errors();
			log_message('error','@@ _do_upload error='.$result);
			log_message('error','@@ _do_upload error_msg='.print_r($this->upload->error_msg,TRUE));
			if ($this->upload->error_msg[0] == 'The image you are attempting to upload exceedes the maximum height or width.') {
				echo "<script type='text/javascript'>";
				echo "	alert('첨부한 이미지의 해상도가 큽니다.');";
				echo "	history.back();";
				echo "</script>";
				exit;
			} elseif ($this->upload->error_msg[0] == 'The file you are attempting to upload is larger than the permitted size.') {
				echo "<script type='text/javascript'>";
				echo "	alert('첨부한 이미지의 파일용량이 큽니다.');";
				echo "	history.back();";
				echo "</script>";
				exit;
			} elseif ($this->upload->error_msg[0] == 'You did not select a file to upload.') {
				return '';
			} else {
				echo "<script type='text/javascript'>";
				echo "	alert('업로드 실패');";
				echo "	history.back();";
				echo "</script>";
				exit;
			}
		}
		
		$result = $this->upload->data();
		$result['file_url'] = $target_url.'/'.$result['file_name'];
		log_message('debug','@@ _do_upload data='.print_r($result,TRUE));
		
		return $result;
	}


	/**
	 * 삭제
	 */
	function remove_ok() {
		log_message('debug', "@@@@ Bbs::remove_ok()");
		
		$idx = $this->input->get('idx', TRUE);
		
		// 글 삭제
		$result = $this->model->remove_bbs($idx);
		if ($result == TRUE) {
			echo "<script type='text/javascript'>";
			echo "alert('삭제되었습니다.');";
			echo "opener.location.reload();";
			echo "window.close();";
			echo "</script>";
			return;
		} else {
			echo "<script type='text/javascript'>";
			echo "alert('삭제 실패');";
			echo "history.back();";
			echo "</script>";
			return;
		}
	}
	
	/**
	 * 댓글 쓰기 완료
	 */
	function reply_ok() {
		log_message('debug', "@@@@ Bbs::reply_ok()");
		
		// 글 저장 (파일이 성공적으로 저장됐을때만 글 저장)
		$bbs_reply['user_id']  = $this->data['sess_userinfo']['user_id'];
		$bbs_reply['nickname'] = $this->data['sess_userinfo']['nickname'];
		$bbs_reply['idx']      = $this->input->post('idx', TRUE);
		$bbs_reply['content']  = $this->input->post('content', TRUE);

		$this->model->insert_bbs_reply($bbs_reply);

		redirect("/bbs/detail?idx=".$bbs_reply['idx']);
	}


	/**
	 * 댓글 삭제
	 */
	function remove_reply_ok() {
		log_message('debug', "@@@@ Bbs::remove_reply_ok()");
		
		$seq = $this->input->get('seq', TRUE);
		$idx = $this->input->get('idx', TRUE);
		
		// 글 삭제
		$this->model->delete_bbs_reply($seq);
		
		redirect("/bbs/detail?idx=".$idx);
	}

	/**
	 * 글 종류 변경 (공지,베스트,비밀글 설정)
	 */
	function modify_type_ok() {
		log_message('debug', "@@@@ Bbs::modify_type_ok()");
		
		$idx       = $this->input->get('idx', TRUE);
		$notice_yn = $this->input->get('notice_yn', TRUE);
		$best_yn   = $this->input->get('best_yn', TRUE);
		$secret_yn = $this->input->get('secret_yn', TRUE);
		
		// 글 삭제
		if ($this->model->update_bbs_type($idx, $notice_yn, $best_yn, $secret_yn)) {
			echo 'true';
		} else {
			echo 'false';
		}
		exit;
	}

}
/* End of file bbs.php */
/* Location: ./application/controllers/star/bbs.php */